#!/usr/bin/env python3

import cv2
import tensorflow as tf
from tensorflow.keras.applications.mobilenet_v2 import decode_predictions
import hashlib
import random
import requests
import json

class BaiduTranslator:
    def __init__(self, appid, secret_key):
        self.appid = appid
        self.secret_key = secret_key
        self.url = "https://fanyi-api.baidu.com/api/trans/vip/translate"

    def translate(self, text, from_lang='en', to_lang='zh'):
        salt = random.randint(32768, 65536)
        sign = hashlib.md5((self.appid + text + str(salt) + self.secret_key).encode()).hexdigest()
        
        params = {
            'q': text,
            'from': from_lang,
            'to': to_lang,
            'appid': self.appid,
            'salt': salt,
            'sign': sign
        }
        
        response = requests.get(self.url, params=params)
        result = json.loads(response.text)
        
        if 'trans_result' in result:
            return result['trans_result'][0]['dst']
        return text

# 初始化百度翻译器（需要用户提供appid和secret_key）
translator = BaiduTranslator(appid='YOUR_APP_ID', secret_key='YOUR_SECRET_KEY')

class VideoAnalyzer:
    def __init__(self):
        self.model = None

    def load_model(self):
        """加载TensorFlow模型"""
        self.model = tf.keras.models.load_model('model.h5')

    def analyze_video(self, video_path: str):
        """分析视频内容并生成标签"""
        if not self.model:
            self.load_model()

        cap = cv2.VideoCapture(video_path)
        if not cap.isOpened():
            raise ValueError(f"无法打开视频文件: {video_path}")

        frames = []
        total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        print(f"视频总帧数: {total_frames}")
        processed_frames = 0

        while True:
            ret, frame = cap.read()
            if not ret:
                break

            resized_frame = cv2.resize(frame, (224, 224))
            tensor = tf.convert_to_tensor(resized_frame, dtype=tf.float32)
            normalized = tensor / 255.0
            batched = tf.expand_dims(normalized, axis=0)

            prediction = self.model.predict(batched)
            decoded_predictions = decode_predictions(prediction, top=1)[0]
            # 获取官方标签（英文描述）
            predicted_class = decoded_predictions[0][1]
            
            # 翻译为中文
            translated = translator.translate(predicted_class)
            frames.append(translated)
            processed_frames += 1

            if processed_frames % 10 == 0:
                progress = (processed_frames / total_frames * 100)
                print(f"处理进度: {progress:.2f}%")

        cap.release()

        if not frames:
            return ["没有处理任何帧"]

        # 统计结果
        unique_classes = list(set(frames))
        class_counts = {cls: frames.count(cls) for cls in unique_classes}

        print("\n视频分析结果：")
        for cls, count in class_counts.items():
            print(f"{cls}: {count} 帧")

if __name__ == "__main__":
    import sys
    
    if len(sys.argv) != 2:
        print("使用方法: python video_analysis.py <视频路径>")
        sys.exit(1)

    analyzer = VideoAnalyzer()
    try:
        analyzer.analyze_video(sys.argv[1])
    except Exception as e:
        print(f"视频分析失败: {str(e)}")